import { AlertCircle, Send } from "lucide-react";
import React, { useId, useState } from "react";
import { redirect, useNavigate } from "react-router";
import type { ArticleCreateInput } from "../../apis/article";
import apis from "../../apis/article";
import useMeStore from "../../store/me";

export default function CreateArticlePage() {
  const { me, loadMe } = useMeStore();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [formData, setFormData] = useState<ArticleCreateInput>({
    title: "",
    content: "",
  });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({
    title: "",
    content: "",
  });

  // 使用 useId 生成唯一 id
  const titleId = useId();
  const contentId = useId();

  // 检查用户是否登录，如果未登录则重定向到登录页
  React.useEffect(() => {
    const checkLoginStatus = async () => {
      await loadMe();
    };

    checkLoginStatus();
  }, [loadMe]);

  // 如果用户未登录，重定向到登录页
  React.useEffect(() => {
    if (me.type !== "loading" && me.type !== "ok") {
      redirect("/login");
    }
  }, [me]);

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));

    // 清除对应字段的错误信息
    if (formErrors[name]) {
      setFormErrors((prev) => ({
        ...prev,
        [name]: "",
      }));
    }
  };

  // 验证表单
  const validateForm = (): boolean => {
    const errors: Record<string, string> = {};

    if (!formData.title.trim()) {
      errors.title = "标题不能为空";
    }

    if (!formData.content.trim()) {
      errors.content = "内容不能为空";
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    if (me.type !== "ok") {
      setError("请先登录");
      return;
    }

    try {
      setLoading(true);
      setError(null);

      const articleId = await apis.articleCreate(formData);

      // 文章创建成功后跳转到文章详情页
      navigate(`/articles/${articleId}`);
    } catch (err) {
      setError("创建文章失败，请稍后再试");
      console.error("Failed to create article:", err);
    } finally {
      setLoading(false);
    }
  };

  // 渲染加载中状态
  if (me.type === "loading") {
    return (
      <div className="min-h-screen bg-base-100 flex flex-col items-center justify-center">
        <div className="loading loading-spinner loading-lg text-primary" />
        <p className="mt-4 text-base-content/70">加载中...</p>
      </div>
    );
  }

  // 如果用户未登录，这里理论上不会执行到，因为已经在前面的 useEffect 中重定向了
  if (me.type !== "ok") {
    return null; // 重定向过程中的占位符
  }

  return (
    <div className="min-h-screen bg-base-100">
      {/* 页面头部 */}
      <header className="bg-base-200 shadow-sm">
        <div className="container mx-auto px-4 py-6">
          <h1 className="text-2xl font-bold text-base-content">创建文章</h1>
        </div>
      </header>

      {/* 表单区域 */}
      <main className="container mx-auto px-4 py-8">
        <div className="max-w-2xl mx-auto bg-base-200 rounded-lg shadow-md p-6">
          {error && (
            <div className="alert alert-error mb-4">
              <AlertCircle className="h-5 w-5 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* 标题输入框 */}
            <div className="space-y-2">
              <label htmlFor={titleId} className="block text-sm font-medium text-base-content">
                标题
              </label>
              <input
                type="text"
                id={titleId}
                name="title"
                value={formData.title}
                onChange={handleInputChange}
                placeholder="请输入文章标题"
                className={`w-full px-4 py-2 border rounded-md focus:ring-2 focus:ring-primary focus:border-primary bg-base-100 text-base-content ${
                  formErrors.title ? "border-red-500" : "border-base-300"
                }`}
                disabled={loading}
              />
              {formErrors.title && <p className="text-sm text-red-500">{formErrors.title}</p>}
            </div>

            {/* 内容输入框 */}
            <div className="space-y-2">
              <label htmlFor={contentId} className="block text-sm font-medium text-base-content">
                内容
              </label>
              <textarea
                id={contentId}
                name="content"
                value={formData.content}
                onChange={handleInputChange}
                placeholder="请输入文章内容"
                rows={10}
                className={`w-full px-4 py-2 border rounded-md focus:ring-2 focus:ring-primary focus:border-primary bg-base-100 text-base-content ${
                  formErrors.content ? "border-red-500" : "border-base-300"
                }`}
                disabled={loading}
              />
              {formErrors.content && <p className="text-sm text-red-500">{formErrors.content}</p>}
            </div>

            {/* 提交按钮 */}
            <div className="pt-4">
              <button type="submit" disabled={loading} className="w-full btn btn-primary">
                {loading ? (
                  <span className="flex items-center justify-center">
                    <div className="loading loading-spinner loading-xs mr-2" />
                    发布中...
                  </span>
                ) : (
                  <span className="flex items-center justify-center gap-2">
                    <Send className="h-5 w-5" />
                    发布文章
                  </span>
                )}
              </button>
            </div>
          </form>
        </div>
      </main>
    </div>
  );
}
